import React from 'react';
import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import {Avatar, Menu, MenuProps, Spin} from 'antd';
import { history, useModel } from 'umi';
import { stringify } from 'querystring';
import HeaderDropdown from './HeaderDropdown';
import styles from './index.less';
import { outLogin } from '@/pages/user/Login/service';
import {removeCookie} from "@/utils/cookie";

export type GlobalHeaderRightProps = {
    menu?: boolean;
};

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
    const msg = await outLogin();
    if(msg.success){
        removeCookie('Aircas-User');
        removeCookie('Aircas-TOKEN');
    }
    const { query = {}, search, pathname } = history.location;
    const { redirect } = query;
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
            pathname: window.location.pathname,
            search: stringify({
                redirect: pathname + search,
            }),
        });
    }
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
    const { initialState, setInitialState } = useModel('@@initialState');
    const currentUser = initialState?.currentUser;

    const onMenuClick: MenuProps['onClick'] = ({ key }) => {
        if (key === 'logout') {
            setInitialState((s) => ({ ...s, currentUser: undefined }));
            loginOut();

            // return;
        }
    };

    // const onMenuClick = useCallback(
    //     (event: MenuInfo) => {
    //         const { key } = event;
    //         if (key === 'logout') {
    //             setInitialState((s) => ({ ...s, currentUser: undefined }));
    //             loginOut();
    //             history.push(window.location.pathname);
    //             // return;
    //         }
    //         // history.push(`/account/${key}`);
    //     },
    //     [setInitialState],
    // );

    const loading = (
        <span className={`${styles.action} ${styles.account}`}>
            <Spin
                size="small"
                style={{
                    marginLeft: 8,
                    marginRight: 8,
                }}
            />
        </span>
    );

    if (!currentUser || !currentUser?.nickName) {
        return loading;
    }

    const menuHeaderDropdown = (
        <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
            {menu && (
                <Menu.Item key="center">
                    <UserOutlined />
                    个人中心
                </Menu.Item>
            )}
            {menu && (
                <Menu.Item key="settings">
                    <SettingOutlined />
                    个人设置
                </Menu.Item>
            )}
            {menu && <Menu.Divider />}

            <Menu.Item key="logout">
                <LogoutOutlined />
                退出登录
            </Menu.Item>
        </Menu>
    );
    return (
        <HeaderDropdown overlay={menuHeaderDropdown}>
            <span className={`${styles.action} ${styles.account}`}>
                <Avatar
                    size="small"
                    className={styles.avatar}
                    src={currentUser.avatarUrl||<UserOutlined/>}
                    alt="avatar"
                />
                <span className={`${styles.name} anticon`}>{currentUser.nickName}</span>
            </span>
        </HeaderDropdown>
    );
};

export default AvatarDropdown;
